package com.tianbing.adlottery.controller.hordeadmin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ModelAndViewDefiningException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fengniu.ejb.business.IUserBusiness;
import com.fengniu.ejb.dao.ICategoryDao;
import com.fengniu.ejb.entity.Category;
import com.fengniu.ejb.entity.User2Site;
import com.tianbing.adlottery.helper.SkinUtils;
import com.tianbing.adlottery.util.UserSession;

public class EditMyHordeProfileInterceptor extends HandlerInterceptorAdapter {
	static Logger logger = Logger.getLogger(EditMyHordeProfileInterceptor.class);

	private SkinUtils skinUtils;

	private String failPage;

	private IUserBusiness userBusiness;

	private ICategoryDao categoryDao;

	/**
	 * 1. check whether the login user has created a store 2. if not created a
	 * store yet, check whether there is an initial sgid parameter 3. etc.
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		UserSession auth = (UserSession) skinUtils.getUserAuthorization(request, response);
		if (auth.getManagedHordeSysId() < 0) {
			User2Site userManagedHorde = userBusiness.findUserManagedHorde(auth.getUserSysId(), -1);
			if (userManagedHorde == null) { // or in black list
				String sgid = ServletRequestUtils.getStringParameter(request, "sgid", null);
				if (sgid == null) {
					ModelAndView modelAndView = new ModelAndView(failPage);
					throw new ModelAndViewDefiningException(modelAndView);
				} else {// we need to check whether sgid is a leaf node
					// 2007-10-09
					List<Category> childs = categoryDao.getListChildCategoryBy(sgid, 0, 1, null);
					if (childs != null && childs.size() > 0) {
						return false;
					}
				}
			} else {
				auth.setManagedHordeSysId(userManagedHorde.getSite().getSysId());
				auth.setManagedHordeName(userManagedHorde.getSite().getName());
			}
		}
		return true;
	}

	public void setFailPage(String viewPage) {
		this.failPage = viewPage;
	}

	public void setSkinUtils(SkinUtils skinUtils) {
		this.skinUtils = skinUtils;
	}

	public void setUserBusiness(IUserBusiness userBusiness) {
		this.userBusiness = userBusiness;
	}

	public static void setLogger(Logger logger) {
		EditMyHordeProfileInterceptor.logger = logger;
	}

	public void setCategoryDao(ICategoryDao categoryDao) {
		this.categoryDao = categoryDao;
	}

}
